package be.vdabantwerpen.gow.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.repackaged.org.joda.time.DateTime;

import be.vdabantwerpen.gow.entities.Post;
import be.vdabantwerpen.gow.entities.GOWUser;
import be.vdabantwerpen.gow.entities.Score;
import be.vdabantwerpen.gow.entities.Weight;
import be.vdabantwerpen.gow.entities.actions.Action;
import be.vdabantwerpen.gow.entities.actions.VisitPostAction;
import be.vdabantwerpen.gow.services.ActionService;
import be.vdabantwerpen.gow.services.ActionServiceImpl;
import be.vdabantwerpen.gow.services.PostService;
import be.vdabantwerpen.gow.services.PostServiceImpl;
import be.vdabantwerpen.gow.services.ScoreService;
import be.vdabantwerpen.gow.services.ScoreServiceImpl;
import be.vdabantwerpen.gow.services.UserService;
import be.vdabantwerpen.gow.services.UserServiceImpl;
import javax.servlet.http.HttpSession;

public class PostServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	private static final String VIEW = "/WEB-INF/JSP/posts/post.jsp";
	private static final PostService postService = new PostServiceImpl();
        private static final ScoreService scoreService = new ScoreServiceImpl();
        private static final ActionService actionService = new ActionServiceImpl();
        private static final UserService userService = new UserServiceImpl();

        @Override
	protected void doGet(HttpServletRequest request, HttpServletResponse 
                response) throws ServletException, IOException
	{
		// errors
		List<String> errors = new ArrayList<String>();

		System.out.println("test");
		Integer postId = null;

		// retrieve postId
		if (request.getParameterMap().containsKey("postId"))
		{
			try
			{
				postId = Integer.parseInt(request.getParameter("postId"));
			} catch (Exception ex)
			{
				System.out.println("NaN");
				errors.add("De parameter 'postId' moet een getal zijn");
			}
		} else
		{
			errors.add("De parameter 'postId' moet gegeven zijn");
		}
		
		// if postId available, retrieve post
		if (postId != null)
		{
			Post post = postService.read(postId);
			if (post != null)
			{
				request.setAttribute("post", post);
                                List<Score> scores = scoreService.findScoresByPost(post);
                                int totalPoints = 0;
                                for(Score score : scores){
                                    totalPoints += score.getValue();
                                }
                                Weight visitPostWeight = actionService.findWeight(
                                        VisitPostAction.class.getName());
                                GOWUser user = post.getUser();
                                Score score = new Score(post, DateTime.now(), 
                                        visitPostWeight.getWeight(), user);
                                scoreService.create(score);
                                request.setAttribute("totalPoints", totalPoints);
                                request.setAttribute("history", scores);
			}
			else
			{
				errors.add("Geen post met die id beschikbaar");
			}
		}

		request.setAttribute("errors", errors);

		RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW);
		dispatcher.forward(request, response);
	}
        
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse 
                response) throws ServletException, IOException {
            GOWUser user = null;
            List<String> errors = new ArrayList();
            HttpSession session = request.getSession();
            if(session != null){
                user = (GOWUser) session.getAttribute("user");
                if(user == null){
                    errors.add("Geen gebruiker");
                }
            }
            
            String content = (String)request.getAttribute("content");
            if(content == null || content.isEmpty()){
                errors.add("Geef een bericht in");
            }
            
            DateTime now = DateTime.now();
            
            if(errors.isEmpty()){
                Post post = new Post(user, now, content);
                postService.create(post);
                response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/posts"));//TODO: adjust redirect
            }
            else {
            	response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/postmaken")); //TODO: go to posting page
            }
        }
        
}
